"use client"

import { useState, useEffect, useRef } from "react"
import { View, Text, TouchableOpacity, StyleSheet, Animated, Platform } from "react-native"
import { theme } from "../../constants/theme"
import { Volume2, BookOpen } from "lucide-react-native"
import { LinearGradient } from "expo-linear-gradient"

interface PhoneticUnit {
    letter: string
    phonetic: string
    color?: string
}

interface NaturalReadingProps {
    word: string
    phoneticUnits: PhoneticUnit[]
    onPlayAudio: (text: string) => Promise<void>
    isPlayingPart: string | null
    translation?: string
    type?: string
    settings?: {
        translationFontSize: number
    }
}

export function NaturalReading({
    word,
    phoneticUnits = [],
    onPlayAudio,
    isPlayingPart,
    translation = "",
    type = "",
    settings = { translationFontSize: 16 },
}: NaturalReadingProps) {
    const [activeIndex, setActiveIndex] = useState<number>(-1)
    const [isPlayingSequence, setIsPlayingSequence] = useState<boolean>(false)
    const [isHighlightingAll, setIsHighlightingAll] = useState<boolean>(false)

    // Animation values for each letter
    const animations = useRef(phoneticUnits.map(() => new Animated.Value(1))).current

    // Extract syllables from the word
    // For this example, we'll use predefined syllables for "formulation"
    const syllables = []
    if (word === "formulation") {
        syllables.push("for", "mu", "la", "tion")
    } else if (word === "favoritism") {
        syllables.push("fa", "vor", "i", "tism")
    } else if (word === "turbine") {
        syllables.push("tur", "bine")
    } else if (word === "supplementary") {
        syllables.push("sup", "ple", "men", "ta", "ry")
    } else if (word === "abandon") {
        syllables.push("a", "ban", "don")
    } else {
        // Simple fallback syllable division
        let currentPos = 0
        while (currentPos < word.length) {
            const syllableLength = Math.min(3, word.length - currentPos)
            syllables.push(word.substring(currentPos, currentPos + syllableLength))
            currentPos += syllableLength
        }
    }

    // Play the animation sequence
    const playSequence = async () => {
        if (isPlayingSequence) return

        setIsPlayingSequence(true)

        // Play each syllable one by one
        for (let i = 0; i < syllables.length; i++) {
            setActiveIndex(i)

            // Find the indices of letters in this syllable
            const syllableStart = word.toLowerCase().indexOf(syllables[i].toLowerCase())
            const syllableEnd = syllableStart + syllables[i].length

            // Animate the letters in this syllable
            for (let j = 0; j < phoneticUnits.length; j++) {
                const letterPos = word
                    .toLowerCase()
                    .indexOf(
                        phoneticUnits[j].letter.toLowerCase(),
                        j > 0 ? word.toLowerCase().indexOf(phoneticUnits[j - 1].letter.toLowerCase()) + 1 : 0,
                    )

                if (letterPos >= syllableStart && letterPos < syllableEnd) {
                    Animated.sequence([
                        Animated.timing(animations[j], {
                            toValue: 1.2,
                            duration: 150,
                            useNativeDriver: true,
                        }),
                        Animated.timing(animations[j], {
                            toValue: 1,
                            duration: 150,
                            useNativeDriver: true,
                        }),
                    ]).start()
                }
            }

            // Play the audio for this syllable
            await onPlayAudio(syllables[i])

            // Wait a bit between syllables
            await new Promise((resolve) => setTimeout(resolve, 300))
        }

        // After playing all syllables, highlight the entire word
        setIsHighlightingAll(true)
        await onPlayAudio(word)

        // Reset after playing the full word
        setTimeout(() => {
            setIsHighlightingAll(false)
            setActiveIndex(-1)
            setIsPlayingSequence(false)
        }, 500)
    }

    // Play sequence on component mount
    useEffect(() => {
        const timer = setTimeout(() => {
            playSequence()
        }, 500)

        return () => clearTimeout(timer)
    }, [word]) // Added word dependency to restart animation when word changes

    // Handle letter press
    const handleLetterPress = async (unit: PhoneticUnit, index: number) => {
        // Animate the letter
        Animated.sequence([
            Animated.timing(animations[index], {
                toValue: 1.2,
                duration: 150,
                useNativeDriver: true,
            }),
            Animated.timing(animations[index], {
                toValue: 1,
                duration: 150,
                useNativeDriver: true,
            }),
        ]).start()

        // Play the sound
        await onPlayAudio(unit.letter)
    }

    // Handle syllable press
    const handleSyllablePress = async (syllable: string, index: number) => {
        setActiveIndex(index)
        await onPlayAudio(syllable)
        setTimeout(() => setActiveIndex(-1), 500)
    }

    // Handle detail press
    const handleDetailPress = () => {
        console.log("Detail button pressed for word:", word)
    }

    return (
        <View style={styles.container}>
            {/* Main word display - single line with colored letters */}
            <LinearGradient
                colors={["#F8F9FF", "#EEF3FF"]}
                style={styles.wordBox}
                start={{ x: 0, y: 0 }}
                end={{ x: 0, y: 1 }}
            >
                <View style={styles.wordContainer}>
                    {phoneticUnits.map((unit, index) => {
                        // Determine if this letter is part of the active syllable
                        let isActive = false
                        if (activeIndex >= 0 && activeIndex < syllables.length) {
                            const syllable = syllables[activeIndex].toLowerCase()
                            const letterPos = word
                                .toLowerCase()
                                .indexOf(
                                    unit.letter.toLowerCase(),
                                    index > 0 ? word.toLowerCase().indexOf(phoneticUnits[index - 1].letter.toLowerCase()) + 1 : 0,
                                )
                            const syllableStart = word.toLowerCase().indexOf(syllable)
                            isActive = letterPos >= syllableStart && letterPos < syllableStart + syllable.length
                        }

                        isActive = isActive || isHighlightingAll

                        return (
                            <Animated.View
                                key={index}
                                style={{
                                    transform: [{ scale: animations[index] }],
                                }}
                            >
                                <TouchableOpacity onPress={() => handleLetterPress(unit, index)} style={styles.letterTouchable}>
                                    <Text style={[styles.letter, { color: unit.color || "#4B7FE5" }, isActive && styles.activeLetter]}>
                                        {unit.letter}
                                    </Text>
                                </TouchableOpacity>
                            </Animated.View>
                        )
                    })}
                </View>
            </LinearGradient>

            {/* Syllable buttons */}
            <View style={styles.syllablesContainer}>
                {syllables.map((syllable, index) => (
                    <TouchableOpacity
                        key={index}
                        style={[styles.syllableButton, activeIndex === index && styles.activeSyllableButton]}
                        onPress={() => handleSyllablePress(syllable, index)}
                    >
                        <LinearGradient
                            colors={activeIndex === index ? ["#5B8EF4", "#4B7FE5"] : ["#F0F5FF", "#E6EEFF"]}
                            style={styles.syllableGradient}
                            start={{ x: 0, y: 0 }}
                            end={{ x: 1, y: 1 }}
                        >
                            <Text style={[styles.syllableText, activeIndex === index && styles.activeSyllableText]}>{syllable}</Text>
                        </LinearGradient>
                    </TouchableOpacity>
                ))}
            </View>

            {/* Phonetic pronunciation with speaker icon */}
            <View style={styles.phoneticContainer}>
                <Text style={styles.phonetic}>
                    {phoneticUnits.map((unit, index) => (
                        <Text key={index} style={{ color: unit.color || theme.colors.neutral.darkGray }}>
                            {index === 0 ? "[" : ""}
                            {unit.phonetic}
                            {index === phoneticUnits.length - 1 ? "]" : ""}
                        </Text>
                    ))}
                </Text>
                <TouchableOpacity style={styles.audioButton} onPress={() => onPlayAudio(word)}>
                    <Volume2 size={16} color={theme.colors.primary.default} />
                </TouchableOpacity>
            </View>

            {/* Translation with adjustable font size */}
            <View style={styles.translationContainer}>
                <Text style={[styles.translationText, { fontSize: settings.translationFontSize }]}>
                    <Text style={styles.typeText}>{type} </Text>
                    {translation}
                </Text>
                <TouchableOpacity style={styles.detailButton} onPress={handleDetailPress}>
                    <BookOpen size={16} color={theme.colors.primary.default} />
                </TouchableOpacity>
            </View>

            {/* Natural Reading Section - compact phonetic buttons */}
            <View style={styles.naturalReadingSection}>
                <LinearGradient
                    colors={["#F8F0F8", "#F0E8F0"]}
                    style={styles.sectionHeaderContainer}
                    start={{ x: 0, y: 0 }}
                    end={{ x: 1, y: 0 }}
                >
                    <Text style={styles.sectionHeader}>自然拼读</Text>
                </LinearGradient>

                <View style={styles.phoneticButtonsContainer}>
                    {phoneticUnits.map((unit, index) => (
                        <TouchableOpacity
                            key={index}
                            style={[styles.phoneticButton, isPlayingPart === unit.letter && styles.activePhoneticButton]}
                            onPress={() => handleLetterPress(unit, index)}
                        >
                            <LinearGradient
                                colors={
                                    isPlayingPart === unit.letter
                                        ? ["rgba(91, 142, 244, 0.3)", "rgba(75, 127, 229, 0.3)"]
                                        : ["rgba(240, 245, 255, 0.8)", "rgba(230, 238, 255, 0.8)"]
                                }
                                style={styles.phoneticButtonGradient}
                                start={{ x: 0, y: 0 }}
                                end={{ x: 0, y: 1 }}
                            >
                                <Text style={[styles.phoneticButtonLetter, { color: unit.color || "#4B7FE5" }]}>{unit.letter}</Text>
                                <Text style={styles.phoneticButtonSound}>{unit.phonetic}</Text>
                            </LinearGradient>
                        </TouchableOpacity>
                    ))}
                </View>
            </View>
        </View>
    )
}

const styles = StyleSheet.create({
    container: {
        padding: theme.spacing.md,
        backgroundColor: "rgba(255, 255, 255, 0.9)",
        borderRadius: theme.borderRadius.large,
        borderWidth: 1,
        borderColor: "rgba(91, 142, 244, 0.15)",
        ...Platform.select({
            ios: {
                shadowColor: "rgba(91, 142, 244, 0.2)",
                shadowOffset: { width: 0, height: 4 },
                shadowOpacity: 0.3,
                shadowRadius: 8,
            },
            android: {
                elevation: 4,
            },
        }),
    },
    // Main word display
    wordBox: {
        alignSelf: "center",
        width: "100%",
        paddingVertical: theme.spacing.lg,
        borderRadius: theme.borderRadius.large,
        marginBottom: theme.spacing.md,
        ...Platform.select({
            ios: {
                shadowColor: "rgba(0, 0, 0, 0.05)",
                shadowOffset: { width: 0, height: 2 },
                shadowOpacity: 0.3,
                shadowRadius: 4,
            },
            android: {
                elevation: 2,
            },
        }),
    },
    wordContainer: {
        flexDirection: "row",
        justifyContent: "center",
        alignItems: "center",
        flexWrap: "nowrap", // Prevent wrapping
        overflow: "visible",
    },
    letterTouchable: {
        padding: 2,
    },
    letter: {
        fontSize: 36, // Slightly larger
        fontWeight: theme.fontWeight.bold,
        textShadowColor: "rgba(0, 0, 0, 0.05)",
        textShadowOffset: { width: 0, height: 1 },
        textShadowRadius: 1,
    },
    activeLetter: {
        opacity: 0.7,
        transform: [{ scale: 1.1 }], // Slightly larger when active
    },
    // Syllable buttons
    syllablesContainer: {
        flexDirection: "row",
        justifyContent: "center",
        alignItems: "center",
        marginBottom: theme.spacing.lg,
        flexWrap: "wrap",
    },
    syllableButton: {
        borderRadius: theme.borderRadius.medium,
        margin: 4,
        overflow: "hidden",
        ...Platform.select({
            ios: {
                shadowColor: "rgba(91, 142, 244, 0.2)",
                shadowOffset: { width: 0, height: 2 },
                shadowOpacity: 0.3,
                shadowRadius: 3,
            },
            android: {
                elevation: 2,
            },
        }),
    },
    syllableGradient: {
        paddingVertical: theme.spacing.sm,
        paddingHorizontal: theme.spacing.lg,
        minWidth: 50,
        alignItems: "center",
    },
    activeSyllableButton: {
        transform: [{ scale: 1.05 }],
    },
    syllableText: {
        fontSize: theme.fontSize.md,
        color: theme.colors.neutral.darkGray,
        fontWeight: theme.fontWeight.medium,
    },
    activeSyllableText: {
        color: theme.colors.neutral.white,
        fontWeight: theme.fontWeight.semiBold,
    },
    // Phonetic pronunciation
    phoneticContainer: {
        flexDirection: "row",
        justifyContent: "center",
        alignItems: "center",
        backgroundColor: "#F5F8FF",
        alignSelf: "center",
        paddingHorizontal: theme.spacing.md,
        paddingVertical: theme.spacing.sm,
        borderRadius: theme.borderRadius.medium,
        marginBottom: theme.spacing.lg,
        borderWidth: 1,
        borderColor: "rgba(91, 142, 244, 0.1)",
    },
    phonetic: {
        fontSize: theme.fontSize.md,
        fontFamily: Platform.OS === "ios" ? "System" : "normal",
        marginRight: theme.spacing.md,
    },
    audioButton: {
        width: 28,
        height: 28,
        borderRadius: 14,
        alignItems: "center",
        justifyContent: "center",
        backgroundColor: "rgba(91, 142, 244, 0.1)",
    },
    // Translation section
    translationContainer: {
        flexDirection: "row",
        justifyContent: "center",
        alignItems: "center",
        marginBottom: theme.spacing.xl, // Increased margin to push natural reading section down
        backgroundColor: "rgba(245, 248, 255, 0.5)",
        padding: theme.spacing.md,
        borderRadius: theme.borderRadius.large,
        borderWidth: 1,
        borderColor: "rgba(91, 142, 244, 0.05)",
    },
    translationText: {
        color: theme.colors.neutral.black,
        textAlign: "center",
        lineHeight: 24,
    },
    typeText: {
        color: theme.colors.primary.default,
        fontWeight: theme.fontWeight.semiBold,
    },
    detailButton: {
        width: 32,
        height: 32,
        borderRadius: 16,
        backgroundColor: "rgba(91, 142, 244, 0.1)",
        alignItems: "center",
        justifyContent: "center",
        marginLeft: theme.spacing.sm,
        ...Platform.select({
            ios: {
                shadowColor: "rgba(91, 142, 244, 0.2)",
                shadowOffset: { width: 0, height: 1 },
                shadowOpacity: 0.3,
                shadowRadius: 2,
            },
            android: {
                elevation: 1,
            },
        }),
    },
    // Natural reading section
    naturalReadingSection: {
        backgroundColor: "rgba(248, 245, 255, 0.5)",
        borderRadius: theme.borderRadius.large,
        padding: theme.spacing.md,
        marginTop: theme.spacing.lg, // Added margin to move section down
        borderWidth: 1,
        borderColor: "rgba(139, 92, 246, 0.1)",
        ...Platform.select({
            ios: {
                shadowColor: "rgba(139, 92, 246, 0.1)",
                shadowOffset: { width: 0, height: 2 },
                shadowOpacity: 0.2,
                shadowRadius: 4,
            },
            android: {
                elevation: 2,
            },
        }),
    },
    sectionHeaderContainer: {
        paddingVertical: 4,
        paddingHorizontal: theme.spacing.md,
        borderRadius: theme.borderRadius.medium,
        marginBottom: theme.spacing.md,
        alignSelf: "flex-start",
    },
    sectionHeader: {
        fontSize: theme.fontSize.sm,
        color: "#8B5CF6",
        fontWeight: theme.fontWeight.semiBold,
    },
    phoneticButtonsContainer: {
        flexDirection: "row",
        flexWrap: "wrap",
        justifyContent: "center",
        alignItems: "center",
        gap: 4, // Reduced gap between buttons
    },
    phoneticButton: {
        borderRadius: theme.borderRadius.small,
        overflow: "hidden",
        margin: 2, // Small margin
        ...Platform.select({
            ios: {
                shadowColor: "rgba(0, 0, 0, 0.1)",
                shadowOffset: { width: 0, height: 1 },
                shadowOpacity: 0.2,
                shadowRadius: 2,
            },
            android: {
                elevation: 1,
            },
        }),
    },
    phoneticButtonGradient: {
        paddingHorizontal: 4, // Narrower buttons
        paddingVertical: 8, // Taller buttons
        alignItems: "center",
        minWidth: 28, // Narrower minimum width
    },
    activePhoneticButton: {
        transform: [{ scale: 1.05 }],
    },
    phoneticButtonLetter: {
        fontSize: theme.fontSize.sm,
        fontWeight: theme.fontWeight.bold,
    },
    phoneticButtonSound: {
        fontSize: 10,
        color: theme.colors.neutral.darkGray,
        fontFamily: Platform.OS === "ios" ? "System" : "normal",
    },
})

